//node.js自带模块
var path = require("path");

//框架与库
var express = require("express");
var favicon = require("serve-favicon");
var session = require("express-session");
var debug = require("debug")("fblog");
var morgan = require("morgan");

var exphbs = require("express-handlebars");
var passport = require("passport");

//自定义模块
//工具
var i18n = require("./utility/i18n");

//自定义路由
var routerEditor = require("./routers/editor");
var routerIndex = require("./routers/index");
var routerAuth = require("./routers/auth");

//自定义中间件
var passportAuth = require("./middlewares/passportAuth");

var app = express();

//设置静态目录
app.use(express.static(path.join(__dirname, "static")));
app.use(favicon(path.join(__dirname, "static", "favicon.ico")));

app.use(morgan("dev"));

// 设置模板引擎
var helpers = {
  __: function() {
    return i18n.__.apply(this, arguments);
  },
  equal: function(param1, param2, options) {
    debug(param1);
    debug(param2);
    if (param1 == param2) {
      debug("equal");
      return options.fn(this);
    } else {
      return options.inverse(this);
    }
  },
  css: function(str, option) {
    var cssList = this.cssList || [];
    str = str.split(/[,，;；]/);
    str.forEach(function(item) {
      if (cssList.indexOf(item) < 0) {
        cssList.push(item);
      }
    });
    this.cssList = cssList.concat();
  },
  js: function(str, option) {
    var jsList = this.jsList || [];
    str = str.split(/[,，;；]/);
    str.forEach(function(item) {
      if (jsList.indexOf(item) < 0) {
        jsList.push(item);
      }
    });
    this.jsList = jsList.concat();
  }
};

app.engine(
  "hbs",
  exphbs({
    helpers: helpers,
    layoutsDir: path.join(__dirname, "views/layouts"),
    partialsDir: path.join(__dirname, "views/partials"),
    defaultLayout: "main",
    extname: ".hbs"
  })
);
app.set("view engine", "hbs");

//设置i18n
app.use(i18n.init);

//设置session
app.use(
  session({
    secret: "fblog-exp-session",
    cookie: {
      maxAge: 24 * 60 * 60 * 1000
    },
    resave: false,
    saveUninitialized: false
  })
);
app.use(express.static(path.join(__dirname, "public")));

//设置passport
app.use(passport.initialize());
app.use(passport.session());
app.use(passportAuth.auth());

//设置路由
app.use("/", routerIndex);
app.use("/", routerAuth);
app.use("/admin", passportAuth.ensureLoggedIn(), routerEditor);

// 如果上面所有的路由都找不到该路径,则跳转到这一个路由处理
// 这个路由,产生一个404的错误
// app.use(function(req, res, next) {
//   var err = new Error();
//   err.status = 404;
//   next(err);
// });

//处理所有产生错误的路由,返回一个渲染错误的页面
// app.use(function(err, req, res, next) {
//   var code = err.status || 500,
//     message = code === 404 ? res.__("error.404_1") : res.__("error.404_2");
//   res.status(code);
//   debug(err);
//   res.render("error", {
//     layout: "other",
//     code: code,
//     message: message
//   });
// });

/**
 * 从进程中获取端口
 */
var normalizePort = function(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

var port = normalizePort(process.env.PORT || "8888");
app.listen(port);
